package com.example.cinema.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.PagerSnapHelper;
import androidx.recyclerview.widget.RecyclerView;

import com.example.cinema.R;
import com.example.cinema.UserAttribute;
import com.example.cinema.adapter.RecyclerAdapter;
import com.example.cinema.adapter.ShortCommentAdapter;
import com.example.cinema.bindingdata.CommentShortData;
import com.example.cinema.bindingdata.ShortBindingData;
import com.example.cinema.bindingdata.UserVideoInfoData;
import com.example.cinema.bindingdata.VideoData;
import com.example.cinema.databinding.ActivityUserplaylistBinding;
import com.example.cinema.databinding.ActivityUservideoListBinding;
import com.example.cinema.drawview.BufferProgress;
import com.example.cinema.drawview.ShortPlayerVideo;
import com.example.cinema.request.RequestData;
import com.example.cinema.request.RequestSend;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;

import java.util.ArrayList;
import java.util.List;

import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;
import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT;

//用户作品上下滑动列表
public class ActivityUserPlayList extends AppCompatActivity {
    @Override
    public void onPause() {
        Log.i("PPPP","失焦");
        if (CurrentPlay != null) {
            CurrentPlay.Playstop();
            if(DialogPlayer!=null)
            {
                DialogPlayer.Playstop();
            }
            Log.i("PPPP","停止");
        }
        super.onPause();
    }

    @Override
    public void onResume() {
        Log.i("PPPP","显示");
        if (CurrentPlay != null && isdialogplayer == false) {
            CurrentPlay.Playstart();
        }else if(isdialogplayer){
            DialogPlayer.Playstart();
        }
        super.onResume();
    }

    @Override
    public void onDestroy() {
        Log.i("PPPP","结束");
        if (CurrentPlay != null) {
            CurrentPlay.Playstop();
            CurrentPlay.Playrelease();
            DialogPlayer.Playstop();
            DialogPlayer.Playrelease();
        }
        super.onDestroy();
    }

    private ActivityUserplaylistBinding AUB;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        AUB = DataBindingUtil.setContentView(this, R.layout.activity_userplaylist);
        initdata();
        init();
        if(Build.VERSION.SDK_INT>11 && Build.VERSION.SDK_INT<19)
        {
            View view = getWindow().getDecorView();
            view.setSystemUiVisibility(View.GONE);
        }else if(Build.VERSION.SDK_INT>=19){
            View view = getWindow().getDecorView();
            int UIOP = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION|View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY|View.SYSTEM_UI_FLAG_FULLSCREEN;
            view.setSystemUiVisibility(UIOP);
        }
    }

    private List<VideoData> datalist;
    private int  current;
    private List<ShortBindingData> shortBindingData = new ArrayList<>();
    private UserVideoInfoData infoData;
    private UserAttribute attribute;
    private void initdata()
    {
        attribute = (UserAttribute) getApplication();
        Intent intent = getIntent();
        current = intent.getIntExtra("position",0);
        String s = intent.getStringExtra("data");
        String u = intent.getStringExtra("udata");
        Gson gson = new Gson();
        datalist = gson.fromJson(s,new TypeToken<List<VideoData>>(){}.getType());
        Log.i("jjjj",datalist.size()+"");
        infoData = gson.fromJson(u,UserVideoInfoData.class);
        for (int i=0;i<datalist.size();i++)
        {
            VideoData vdata = datalist.get(i);
            ShortBindingData sbdata = new ShortBindingData();
            sbdata.image.set(vdata.videoimge.get());
            sbdata.playurl.set(vdata.videoshort.get());
            sbdata.title.set(vdata.videoname.get());
            sbdata.imgurl.set(infoData.userimg.get());
            sbdata.useruid.set(infoData.usersid.get());
            sbdata.videourl.set(vdata.videourls.get());
            sbdata.texts.set(vdata.videobrief.get());
            sbdata.videoid.set(vdata.videosid.get());
            shortBindingData.add(sbdata);
        }
        videoid = shortBindingData.get(current).videoid.get();
        currentdata = shortBindingData.get(current);

    }


    private RecyclerAdapter adapter;
    private int Prev;
    private ShortPlayerVideo PrevPlay;
    private ShortPlayerVideo CurrentPlay;
    private String videoid;
    private ShortBindingData currentdata;
    private List<CommentShortData> cmmentdata = new ArrayList<>();
    private int scrolly;
    private View Cview;
    private void init()
    {
        AUB.recycler.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false));
        new PagerSnapHelper().attachToRecyclerView(AUB.recycler);
        adapter = new RecyclerAdapter(shortBindingData,R.layout.short_video_item,getApplicationContext());
        AUB.recycler.setAdapter(adapter);
        AUB.recycler.scrollToPosition(current);
        //滚动
        AUB.recycler.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                LinearLayoutManager manager = (LinearLayoutManager) recyclerView.getLayoutManager();//减Relcycler的布局转换为线性管理器
                int t = manager.findLastVisibleItemPosition();
                int len = manager.getItemCount();//获取子View总数
                if(newState == RecyclerView.SCROLL_STATE_DRAGGING)//判断状态正在拖动的
                {
                    Prev  = manager.findLastCompletelyVisibleItemPosition();//获取正在拖到的Item索引
                    View Pview = manager.findViewByPosition(Prev);//根据索引获取ItemView
                    Log.i("KKK",Prev+"");
                    if(Pview==null){//判断是否空
                        return;
                    }
                    PrevPlay = Pview.findViewById(R.id.player);//获取Item中的视频播放View

                }
                if(newState==RecyclerView.SCROLL_STATE_IDLE)//判断状态拖动停止
                {
                    cmmentdata.clear();//清空评价数据
                    int y = Math.abs(scrolly);//负数转数值
                    int current = manager.findLastCompletelyVisibleItemPosition();//获取当前完全可见的Item索引
                    if(current<0)//判断如果小于0 则不做任何处理 比如没有滑动完成 获取的索引会是-1
                    {
                        return;
                    }
                    videoid = shortBindingData.get(current).videoid.get();
                    Log.i("HHHH",shortBindingData.get(current).title.get());
                    currentdata = shortBindingData.get(current);
                    Cview = manager.findViewByPosition(current);//获取当前可见ItemView对象
                    BufferProgress progress = Cview.findViewById(R.id.progress);
                    progress.Animators();
                    CurrentPlay = Cview.findViewById(R.id.player);//获取Item中的播放器View
                    int height = CurrentPlay.getHeight();//获取高度用来跟 滚动的Y坐标进行对别判断是否完成了滚动
                    if(y>(height-100))
                    {
                        PrevPlay.Playstop();//停止上一个播放器
                        PrevPlay.Playrelease();//释放上一个播放器
                        Log.i("PPP","滚动成功");
                        CurrentPlay.loadVideo();//开始当前ItemView播放器播放
                        IsFollow();
                    }
                    scrolly=0;//将计数Y坐标清空为0
                }
            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                Log.i("YYY", scrolly + "");
                scrolly += dy;//计数滑动的Y值
            }
        });
        //分享点击
        adapter.setShareClick(new RecyclerAdapter.onShareClickListener() {
            @Override
            public void ShareClick() {
                sharedata();
            }
        });
        //头像点击
        adapter.setUserClick(new RecyclerAdapter.onUserImgClickListener() {
            @Override
            public void UserImgClick() {

            }
        });
        //点击完整
        adapter.setVipClick(new RecyclerAdapter.onVipVideoClickListener() {
            @Override
            public void VipClick() {
                Log.i("HHHS","看完成");
                new Thread()
                {
                    @Override
                    public void run() {
                        if(attribute.getUID()==null)
                        {
                            handler.sendEmptyMessage(1004);
                            return;
                        }
                        RequestSend send = new RequestSend(getApplicationContext());
                        boolean b = send.VipCheck(attribute.getUID());
                        if(b)
                        {
                            if(currentdata==null)
                            {
                                return;
                            }
                            GetVurl();
                        }else {
                            handler.sendEmptyMessage(1003);
                        }
                    }
                }.start();
            }
        });
        //评论点击
        adapter.setCommentclick(new RecyclerAdapter.onCommentClickListener() {
            @Override
            public void CommentClick() {
                if(cmmentdata.size()<1)
                {
                    GetComment();
                }
                commentdata();
            }
        });
        //返回
        AUB.finsh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        InitDialog();
    }
    //提取播放链接
    private void GetVurl()
    {
        new Thread()
        {
            @Override
            public void run() {
                Log.i("HHH",currentdata.videoid.get()+"----ID");
                RequestData requestData = new RequestData(getApplicationContext());
                String url = requestData.GetVipUrl(currentdata.videoid.get(),attribute);
                Log.i("HHH","获取到播放"+url);
                if(url!=null)
                {
                    Message message = new Message();
                    message.what = 1005;
                    message.obj = url;
                    handler.sendMessage(message);
                }
            }
        }.start();
    }

    //检查是否已关注
    private void IsFollow(){
        new Thread(){
            @Override
            public void run() {
                Log.i("MMMSS",attribute.getUID());
                Log.i("MMMSS",currentdata.useruid.get());
                RequestSend requestSend = new RequestSend(getApplicationContext());
                boolean bool = requestSend.isFollow(attribute.getUID(),currentdata.useruid.get(),attribute);
                Message message = new Message();
                message.what = 1007;
                message.obj = bool;
                handler.sendMessage(message);
            }
        }.start();
    }
    //弹出评论区
    private AlertDialog dialog;
    private ShortCommentAdapter scadapter;
    private EditText editText;
    private void commentdata()
    {
        View view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.comment_dialog,null);
        dialog = new AlertDialog.Builder(this)
                .setView(view)
                .create();
        ListView listView = view.findViewById(R.id.commentlist);
        scadapter = new ShortCommentAdapter(getApplicationContext(),cmmentdata,R.layout.comment_item);
        listView.setAdapter(scadapter);
        dialog.show();



        int width = getResources().getDisplayMetrics().widthPixels;
        Window window = dialog.getWindow();
        window.setGravity(Gravity.BOTTOM);
        window.getDecorView().setMinimumWidth(width);
        window.getDecorView().setPadding(0,0,0,0);
        window.getDecorView().setBackgroundResource(R.drawable.dialog_round_bag);
        WindowManager.LayoutParams params = window.getAttributes();
        params.width =width;
        params.height= WRAP_CONTENT;
        window.setWindowAnimations(R.style.dialoganim);
        window.setAttributes(params);
        //评论点赞
        scadapter.SetZanListener(new ShortCommentAdapter.OnZanListener() {
            @Override
            public void ZanClick(ImageView view, int positon, Object data) {
                view.getDrawable().setLevel(2);
                RequestSend requestSend = new RequestSend(getApplicationContext());
                CommentShortData shortData = (CommentShortData) data;
                new Thread()
                {
                    @Override
                    public void run() {
                        boolean b = requestSend.SendUserZan(videoid,shortData.usersid.get());
                        if(b)
                        {
                            int z = Integer.valueOf( shortData.zannumbe.get());
                            shortData.zannumbe.set(String.valueOf(z+1));
                        }
                    }
                }.start();
            }
        });
        //提交评论
        editText = view.findViewById(R.id.text);
        ImageView sendimg = view.findViewById(R.id.sendbtn);
        //提交评论
        sendimg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(attribute.getToken()==null||attribute.getUID()==null)
                {
                    Intent intent = new Intent();
                    intent.setAction("sign");
                    startActivity(intent);
                    return;
                }
                String text = editText.getText().toString();
                if(text.isEmpty())
                {
                    Toast.makeText(getApplicationContext(),"内容不能为空",Toast.LENGTH_SHORT).show();
                    return;
                }
                String ss = text.replace(" ","");
                if(ss.length()<1)
                {
                    Toast.makeText(getApplicationContext(),"内容不能为空",Toast.LENGTH_SHORT).show();
                    return;
                }
                new Thread()
                {
                    @Override
                    public void run() {
                        RequestSend send = new RequestSend(getApplicationContext());
                        boolean b = send.SendAssess(currentdata.videoid.get(),attribute.getUID(),text);
                        Message message = new Message();
                        message.what = 1006;
                        message.obj = b;
                        handler.sendMessage(message);
                    }
                }.start();
            }
        });
    }
    //获取评论数据
    private int cp =1;
    private int cl =30;
    private void GetComment()
    {
        new Thread(){
            @Override
            public void run() {
                RequestData requestData = new RequestData(getApplicationContext());
                Log.i("QQSSQ",videoid);
                List<CommentShortData> data = requestData.GetShortComment(videoid,cp,cl);
                cmmentdata.addAll(data);
                handler.sendEmptyMessage(1002);
            }
        }.start();
    }
    //弹出分享区
    private AlertDialog shareDialog;
    private void sharedata()
    {
        View view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.share_dialog,null);
        shareDialog = new AlertDialog.Builder(getApplicationContext())
                .setView(view).create();
        LinearLayout wx = view.findViewById(R.id.wxclick);
        LinearLayout qq = view.findViewById(R.id.qqclick);

        shareDialog.show();
        int width = getResources().getDisplayMetrics().widthPixels;
        Window window = shareDialog.getWindow();
        window.setGravity(Gravity.BOTTOM);
        window.getDecorView().setMinimumWidth(width);
        window.getDecorView().setPadding(0,0,0,0);
        window.getDecorView().setBackgroundResource(R.drawable.dialog_round_bag);
        WindowManager.LayoutParams params = window.getAttributes();
        params.width =width;
        params.height= WindowManager.LayoutParams.WRAP_CONTENT;
        window.setWindowAnimations(R.style.dialoganim);
        window.setAttributes(params);


        //微信分享点击
        wx.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        //QQ分享点击
        qq.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
    }
    //弹出完整播放
    private AlertDialog alertDialog;
    private ShortPlayerVideo DialogPlayer;
    private boolean isdialogplayer = false;
    private void InitDialog()
    {
        if(CurrentPlay!=null)
        {
            CurrentPlay.Playstop();
        }
        int h = getResources().getDisplayMetrics().heightPixels;
        int w = getResources().getDisplayMetrics().widthPixels;
        DialogPlayer = new ShortPlayerVideo(getApplicationContext());
        LinearLayout.LayoutParams layoutParamss = new LinearLayout.LayoutParams(MATCH_PARENT,MATCH_PARENT);
        layoutParamss.width = w;
        layoutParamss.height = h;
        layoutParamss.gravity = Gravity.CENTER;
        DialogPlayer.setLayoutParams(layoutParamss);

        //重叠容器
        FrameLayout frameLayout = new FrameLayout(getApplicationContext());
        frameLayout.addView(DialogPlayer);


        //返回
        FrameLayout.LayoutParams layoutParams  = new FrameLayout.LayoutParams(60,60);
        layoutParams.topMargin=20;
        layoutParams.leftMargin=20;
        ImageView close = new ImageView(getApplicationContext());
        close.setLayoutParams(layoutParams);
        close.setImageResource(R.mipmap.fanhui);
        frameLayout.addView(close);

        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(MATCH_PARENT,MATCH_PARENT);
        params.gravity = Gravity.CENTER;
        params.width = w;
        params.height = h;
        frameLayout.setLayoutParams(params);


        DialogPlayer.setBackgroundColor(Color.BLACK);
        alertDialog = new AlertDialog.Builder(this)
                .setView(frameLayout)
                .create();
        Window window = alertDialog.getWindow();
        window.getDecorView().setBackgroundColor(Color.RED);
        window.getDecorView().setPadding(0,0,0,0);
        WindowManager.LayoutParams wparam = window.getAttributes();
        wparam.width = w;
        wparam.height= h;
        wparam.gravity = Gravity.CENTER;
        window.setAttributes(wparam);
        alertDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                isdialogplayer = false;
                DialogPlayer.Playstop();
                DialogPlayer.Playrelease();
            }
        });
        //关闭
        close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.cancel();
            }
        });
    }


    Handler handler = new Handler(Looper.getMainLooper())
    {
        @Override
        public void handleMessage(@NonNull Message msg) {
            if (msg.what == 1000) {
                adapter.notifyDataSetChanged();
            }

            if (msg.what == 1003) {
                Toast.makeText(getApplicationContext(), "您还不是VIP哦", Toast.LENGTH_LONG).show();
            }
            if (msg.what == 1004) {

                Intent intent = new Intent();
                intent.setAction("sign");
                startActivity(intent);
                return;
            }
            if (msg.what == 1005) {
                isdialogplayer = true;
                if (CurrentPlay != null)
                {
                    CurrentPlay.Playstop();
                }
                if(PrevPlay!=null)
                {
                    PrevPlay.Playstop();
                }
                alertDialog.show();
                Log.i("IMG","----------------------------");
                Log.i("IMG",currentdata.imgurl.get());
                Log.i("IMG","----------------------------");
                DialogPlayer.setImgUrl(currentdata.imgurl.get());
                DialogPlayer.setPlayurl((String) msg.obj);
                DialogPlayer.loadVideo();
            }

            if (msg.what == 1006)
            {
                boolean bol = (boolean) msg.obj;
                if(bol)
                {
                    Toast.makeText(getApplicationContext(),"评价成功,审核后显示",Toast.LENGTH_SHORT).show();
                    editText.setText(null);
                }else {
                    Toast.makeText(getApplicationContext(),"评价失败。",Toast.LENGTH_SHORT).show();
                }
                return;
            }

            if(msg.what == 1007)
            {
                boolean abb = (boolean) msg.obj;
                ImageView  follows = Cview.findViewById(R.id.follow);
                if(abb)
                {

                    follows.setVisibility(View.INVISIBLE);
                }else {
                    follows.setVisibility(View.GONE);
                }
            }
        }
    };
}
